package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.mapper.SetmealMapper;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;


@Service
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    //新增套餐
    @Transactional
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealMapper.add(setmeal);

        if (checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer checkgroupId : checkgroupIds) {
                setmealMapper.addSetmealAndCheckGroup(setmeal.getId(), checkgroupId);
            }
        }
        //将有用的图片地址保存到redis
        redisTemplate.opsForSet().add("imgUrlend", setmeal.getImg());
    }

    //根据id查询套餐
    public Setmeal findById(Integer id) {
        return setmealMapper.findById(id);
    }

    //编辑套餐
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        //修改套餐
        setmealMapper.edit(setmeal);
        //删除套餐和检查组的关联关系
        setmealMapper.editAndCheckGroup(setmeal.getId());

        if (checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer checkgroupId : checkgroupIds) {
                setmealMapper.addSetmealAndCheckGroup(setmeal.getId(), checkgroupId);
            }
        }
        //将图片地址保存到redis
        redisTemplate.opsForSet().add("imgUrlend", setmeal.getImg());
    }

    //查询所有套餐
    public List<Setmeal> findAll() {
        return setmealMapper.findAll();
    }

    //分页条件查询

    @Override
    public PageResult findPage(QueryPageBean queryPage) {
        //设置分页查询条件
        PageHelper.startPage(queryPage.getCurrentPage(), queryPage.getPageSize());
        List<Setmeal> page = setmealMapper.findPage(queryPage);
        Page<Setmeal> p = (Page<Setmeal>) page;

        return new PageResult(p.getTotal(), p.getResult());
    }
}
